const sql = require('../../sql/sqlConfig');
const pagination = require('../../util/page');
const express = require('express');
let router = express.Router();
const tokenObj = require('../../util/jwt');

//验证token
let myToken = new tokenObj();
let userId;
router.use('/', function (req, res, next) {
    let token = req.headers.token;
    myToken.checkToken(token,function(flag){
        if(!flag) return res.send({errCode:401,message:'登陆失效了'});
        else {
            userId = flag;
            next()
        }
    });
});

// 查我的订单
router.get('/myOrder', function (req, res, next) {
    let countPageSql = "select count(`id`) as total from `order` where `user_id`="+userId;
    let page = req.query.page;
    let option = "select o.`id`, o.`create_time`, p.`name` as productName, p.`disc` as productDisc, o.`price` as productPrice, p.`pic` as productPic, o.`address`, o.`num`, o.`total_price`, o.`order_payment_status` from `order` as o, `product` as p where p.`id`=o.`product_id` and o.`user_id`="+userId+" order by o.`id` desc limit ";
    pagination(countPageSql,page,option,function (result) {
        return res.send(result)
    });
});

// 查我的地址多条
router.get('/addressList', function (req, res, next) {
    let countPageSql = "select count(`id`) as total from `address` where `user_id`="+userId;
    let page = req.query.page;
    let option = "select * from `address` where `user_id`="+userId+" limit ";
    pagination(countPageSql,page,option,function (result) {
        return res.send(result)
    });
});

// 查我的地址单条
router.get('/addressItem', function (req, res, next) {
    let id = req.query.id;
    let option = "select * from `address` where `id` = "+id;
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
        if(!rows[0]) return  res.send({errCode:9,message:'查不到该条地址的详细信息'});
        return res.send({errCode:0,message:'查询该条地址信息成功',result:rows[0]});
    })
});

//新增地址
router.post('/addAddress', function (req, res, next) {
   let {receiver_name,phone,address,status} = req.body.addressInfo;
   let errFlag = 0;//可以新增地址的标志（主要是验证全局状态的改变）
    if(status){//将该用户的地址默认状态都改成0
        let option = "select `id` from `address` where `user_id`="+userId;
        sql.query(option, function (err, rows) {
            if (err){
                errFlag = 1;
                return res.send({errCode:-9999,message:'操作数据库失败'+err});
            }
            if(rows.length>0){
               let addressIdList = [];
                rows.forEach((val,index,arr)=>{
                    addressIdList.push(val.id)
                });
                let updateSql = "update `address` set `status`=0 where `user_id`="+userId+" and `id` in ("+[...addressIdList]+")";
                sql.query(updateSql, function (err, rows) {
                    if (err){
                        errFlag = 1;
                        return res.send({errCode:-9999,message:'操作数据库失败'+err});
                    }
                    insertAddress()
                });
                if(errFlag) return false
            }else{
                insertAddress()
            }
        });
        if(errFlag) return false
    }else{
        insertAddress()
    }
    //再插入
    function insertAddress() {
        let insertSql = "insert into `address`(`receiver_name`,`phone`,`address`,`status`,`user_id`) values('" + receiver_name + "','" + phone + "','" + address + "'," + status + "," + userId + ")";
        sql.query(insertSql, function (err, rows) {
            if (err) return res.send({errCode: -9999, message: '操作数据库失败' + err});
            res.send({errCode: 0, message: '新增地址成功'});
        })
    }
});

//修改地址
router.post('/updateAddress', function (req, res, next) {
    let {id,receiver_name,phone,address,status} = req.body.addressInfo;
    let errFlag = 0;//可以新增地址的标志（主要是验证全局状态的改变）
    if(status){
        let option = "select `id` from `address` where `user_id`="+userId;
        sql.query(option, function (err, rows) {
            if (err){
                errFlag = 1;
                return res.send({errCode:-9999,message:'操作数据库失败'+err});
            }
            if(rows.length>0){//将该用户的地址默认状态都改成0
                let addressIdList = [];
                rows.forEach((val,index,arr)=>{
                    addressIdList.push(val.id)
                });
                let updateSql = "update `address` set `status`=0 where `user_id`="+userId+" and `id` in ("+[...addressIdList]+")";
                sql.query(updateSql, function (err, rows) {
                    if (err){
                        errFlag = 1;
                        return res.send({errCode:-9999,message:'操作数据库失败'+err});
                    }
                    updateAddress()
                });
                if(errFlag) return false
            }else{
                updateAddress()
            }
        });
        if(errFlag) return false
    }else{
        updateAddress()
    }
    //修改
    function updateAddress(){
        let updateSql = "update `address` set `receiver_name`='" + receiver_name + "',`phone`='" + phone + "',`address`='" + address + "',`status`=" + status  + " where `id`=" + id;
        sql.query(updateSql, function (err, rows) {
            if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
            return res.send({errCode:0,message:'修改地址成功'});
        })
    }
});

//删除地址
router.post('/removeAddress', function (req, res, next) {
    let id = req.body.id;
    let option =  "DELETE FROM `address` WHERE `id` = "+id;
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
        res.send({errCode:0,message:"该条地址已删除"});
    })
});

//获取默认地址
router.get('/defaultAddress', function (req, res, next) {
    let option = "select * from `address` where `user_id`="+userId+" and `status`=1";
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
        if(!rows[0]) return  res.send({errCode:9,message:'查不到默认地址的详细信息'});
        res.send({errCode:0,message:'查询默认地址信息成功',result:rows[0]});
    })
});

//查用户等级
function getUserLevel(id,fn){
    let option = "select sum(`num`) as total from `order` where `order_payment_status`=1 and `pid`="+id+" group by `pid`";
    sql.query(option, function (err, rows) {
        if (err) return fn(0,err);
        let count = rows.length>0?rows[0].total:0;//用户分享成功的单数
        let option1 = "select * from `level_setting` where `order_num`<="+count;//找到1、2级，用户分享的单子都比这几级大
        sql.query(option1, function (err1, rows1) {
            if (err1) return fn(0,err1);
            let maxNum = Math.max.apply(Math, rows1.map(function(val) {return val.order_num}));//找到2级
            let result = {};
            rows1.forEach((val,index,arr)=>{
                if(val.order_num==maxNum)
                    return result=val;
            });
            return fn(1,result)
        })
    })
}

//查分销商等级
router.get('/myLevel', function (req, res, next) {
    getUserLevel(userId,function (flag,info) {
        if(!flag) return res.send({errCode: -9999, message: '操作数据库失败' + info});
        let level = info.level;
        return res.send({errCode:0,message:'查询用户分销商等级成功',level:level})
    });
});

//支付接口
router.post('/pay', function (req, res, next) {
    let {product_id,price,num,total_price,address,order_payment_status,pid} = req.body;
    let option = "insert into `order`(`product_id`,`price`,`num`,`total_price`,`address`,`order_payment_status`,`user_id`,`pid`) values("
        + product_id + "," + price + "," + num +"," + total_price + ",'" + address + "'," +order_payment_status + "," +userId + "," + pid +")";
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
        let orderId = rows.insertId;//支付成功的订单id
        if(order_payment_status==0) return res.send({errCode:9,message:'已取消支付，该订单未完成'});
        if(pid==0) return res.send({errCode:0,message:'支付成功'});
        if(order_payment_status==1 && pid!=0){
            //拿pid查佣金
            getUserLevel(pid,function (flag,info) {
                if(!flag) return res.send({errCode: -9999, message: '操作数据库失败' + info});
                let proportion = info.proportion;
                //拿product_id查商品利润
                let getProfitSql = "select `price`, `principal` from `product` where `id` = "+product_id;
                sql.query(getProfitSql, function (err, rows) {
                    if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
                    let profit = rows[0].price-rows[0].principal;
                    let commission = Math.floor((profit*(proportion.replace("%","")/100)*num) * 100) / 100;
                    let insertCommissionSql = "insert into `commission`(`user_id`,`order_id`,`money`) values(" + pid + "," + orderId +"," + commission +")";
                    sql.query(insertCommissionSql, function (err, rows) {
                        if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
                        return res.send({errCode:0,message:'支付成功'});
                    })
                })
            });
        }
    })
});

//查用户的累计分销佣金
router.get('/myMoneyAll', function (req, res, next) {
    let option = "select sum(`money`) as allMoney from `commission` where `user_id` = "+userId;
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
        let allMoney = +(rows[0].allMoney);
        return res.send({errCode:0,message:'查询用户总佣金成功',allMoney:allMoney})
    })
});

//用户未提现佣金
router.get('/balance', function (req, res, next) {
    //先在提现表统计一下以前提现了多少
    //再去订单表获取总佣金
    //总佣金-总提现
    let option = "select sum(`money`) as isCashOuted from `cash_out` where `user_id` = "+userId;
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
        let isCashOuted = +(rows[0].isCashOuted);//已经提现的金额
        let allCommissionSql = "select sum(`money`) as allMoney from `commission` where `user_id` = "+userId;
        sql.query(allCommissionSql, function (err, rows) {
            if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
            let allMoney = +(rows[0].allMoney);//总佣金
            let balance = Math.floor((allMoney-isCashOuted) * 100) / 100;//未提现余额
            return res.send({errCode:0,message:'查询用户可提取佣金成功',balance:balance})

        })
    })
});

//用户提现
router.post('/getCashOut', function (req, res, next) {
    let money = req.body.money;
    let option = "select sum(`money`) as isCashOuted from `cash_out` where `user_id` = "+userId;
    sql.query(option, function (err, rows) {
        if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
        let isCashOuted = +(rows[0].isCashOuted);//已经提现的金额
        let allCommissionSql = "select sum(`money`) as allMoney from `commission` where `user_id` = "+userId;
        sql.query(allCommissionSql, function (err, rows) {
            if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
            let allMoney = +(rows[0].allMoney);//总佣金
            let balance = allMoney-isCashOuted;//未提现余额
            if(money>balance){//要提现的钱比账上还多
                return res.send({errCode:9,message:'没有那么多钱可以提现啦'});
            }
            let insertCashOutSql = "insert into `cash_out`(`user_id`,`money`) values(" + userId + "," + money +")";
            sql.query(insertCashOutSql, function (err, rows) {
                if (err) return res.send({errCode:-9999,message:'操作数据库失败'+err});
                return res.send({errCode:0,message:'提现成功'});
            })
        })
    })
});

//查分销订单
router.get('/myCommissionOrder', function (req, res, next) {
    let countPageSql = "select count(`id`) as total from `commission` where `user_id`="+userId;
    let page = req.query.page;
    let option = "select c.`order_id`, o.`create_time`, u.`email`, o.`total_price`, c.`money` from `order` as o, `commission` as c, `user` as u where o.`id`=c.`order_id` and u.`id`=o.`user_id` and c.`user_id`="+userId+" order by c.`id` desc limit ";
    pagination(countPageSql,page,option,function (result) {
        return res.send(result)
    });
});


module.exports = router;
